package jmine.tec.utils;

/**
 * Implementacao abstrata de uma tupla. Implementa {@link #equals(Object)}, {@link #hashCode()} e {@link #toString()}
 * 
 * @author takeshi.fukushima
 * @param <H>
 * @param <T>
 */
public abstract class AbstractTuple<H, T> implements Tuple<H, T> {

    /**
     * Este equals nao verifica se a classe é exatamente igual - apenas se o outro lado obedece à interface {@link Tuple}
     * <p>
     * {@inheritDoc}
     */
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Tuple<?, ?>)) {
            return false;
        }
        Tuple<?, ?> other = (Tuple<?, ?>) obj;
        if (notEquals(this.getHead(), other.getHead()) || notEquals(this.getTail(), other.getTail())) {
            return false;
        }
        return true;
    }

    /**
     * O hashcode gerado leva em consideracao apenas o {@link #head()} e o {@link #tail()}
     * <p>
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        int hash = 0;
        final int prime = 7;
        H head = this.getHead();
        T tail = this.getTail();
        if (head != null) {
            hash = prime * (hash | head.hashCode());
        }
        if (tail != null) {
            hash = prime * (hash | tail.hashCode());
        }
        return hash;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return "{ " + String.valueOf(this.getHead()) + ", " + String.valueOf(this.getTail()) + "+";
    }

    /**
     * @param first the first element
     * @param second the second element
     * @return boolean
     */
    private static boolean notEquals(Object first, Object second) {
        if (first == second) {
            return false;
        }
        if (first == null) {
            return second == null;
        } else if (second == null) {
            return false;
        } else {
            return !first.equals(second);
        }
    }

    /**
     * {@inheritDoc}
     */
    public MutableTuple<H, T> toMutable() {
        return MutableTuple.newTuple(this.getHead(), this.getTail());
    }

    /**
     * {@inheritDoc}
     */
    public Tuple<H, T> toUnmodifiable() {
        return new UnmodifiableTuple<H, T>(this.getHead(), this.getTail());
    }

    /**
     * Este metodo usa o {Tuple#copy()} para clonar
     * <p>
     * {@inheritDoc}
     */
    @Override
    public Object clone() {
        return this.copy();
    }

    /**
     * {@inheritDoc}
     */
    public final H head() {
        return this.getHead();
    }

    /**
     * {@inheritDoc}
     */
    public final T tail() {
        return this.getTail();
    }

}
